package com.utils.httpclient;

import java.io.BufferedInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.common.collect.Maps;

public class HttpClientGet/* extends HttpClientAdapter*/ {
	
	private static int MAX_TIMEOUT = 3000; 
//	private static PoolingHttpClientConnectionManager connMgr;  
    private static RequestConfig requestConfig;  
     
  
    static {  
        // 设置连接池  
//        connMgr = new PoolingHttpClientConnectionManager();  
//        // 设置连接池大小  
//        connMgr.setMaxTotal(100);  
//        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  
        
//        connMgr.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());

        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
        // 在提交请求之前 测试连接是否可用  
        configBuilder.setStaleConnectionCheckEnabled(true);  
//        configBuilder.setRedirectsEnabled(false);
        requestConfig = configBuilder.build();  
    }
	
    public static void setTimeOut(int timeOut) {
    	MAX_TIMEOUT = timeOut;
    }
//    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
//            .setConnectionRequestTimeout(15000).build();
	// 创建默认的httpClient实例

    private static CloseableHttpClient  httpClient = HttpClients.createDefault();
    private static Map<String, String> header = new HashMap<String, String>();
    
    // 单例模式
//    private HttpClientGet instance = null;
//    private HttpClientGet() {
//    	
//    }
/*    public static HttpClientGet getInstance() {
    	if (instance == null) {
    		instance = new HttpClientGet();
    	}
    	return instance;
    }*/
    
    public static void setHeader(Map<String, String> headers) {
    	headers.put("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
    	headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    	headers.put("Accept-Language", "zh-CN");
    	headers.put("Connection", "Keep-Alive");
    	headers.put("Content-Type", "text/html; charset=UTF-8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36");
		header = headers;
    }
    
	public static void  creatProxyHttpClient(String hostName, int port) {
		// 使用代理服务器
		httpClient = HttpClients.custom().setProxy(new HttpHost(hostName, port)).build();
	}

	public static void createDefaultHttpClient() {
		// 创建默认的httpClient实例
//		httpClient = HttpClients.custom()
//	            .setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build())
//	            .build();
		
		 httpClient = HttpClients.createDefault();
	}
	
    /**
     * 发送Get请求 http://
     * @param httpPost
     * @return
     */
//	@Override
    public static String sendHttpGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpGet.setConfig(requestConfig);
            for (String key : header.keySet()) {
            	httpGet.addHeader(key, header.get(key));	
			}
            response = httpClient.execute(httpGet);
            if(200==response.getStatusLine().getStatusCode()) {
	            entity = response.getEntity();
	            responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }
    
    /**
     * 发送Get请求 http://
     * @param httpPost
     * @return
     */
//	@Override
    public static String sendHttpGet(String httpUrl,String unicode) {
		HttpGet httpGet = new HttpGet(httpUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpGet.setConfig(requestConfig);
            for (String key : header.keySet()) {
            	httpGet.addHeader(key, header.get(key));	
			}
            response = httpClient.execute(httpGet);
            if(200==response.getStatusLine().getStatusCode()) {
            	entity = response.getEntity();
            	responseContent = EntityUtils.toString(entity, unicode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
          /*  try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }*/
        }
        return responseContent;
    }
    
    public static String sendHttpGetAndReturnHeader(String httpUrl,String unicode) {
		HttpGet httpGet = new HttpGet(httpUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        String newuri="";
        try {
            httpGet.setConfig(requestConfig);
            for (String key : header.keySet()) {
            	httpGet.addHeader(key, header.get(key));	
			}

            response = httpClient.execute(httpGet);
            //----------判断是否重定向开始
//            response.setHeader("Content-Type", "text/html; charset=utf-8");


            int code = response.getStatusLine().getStatusCode();
            if(302==code) {
            	Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
                newuri = header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请，以便得到跳转后的信息是啥。
                System.out.println(newuri);
                return newuri;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
          /*  try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }*/
        }
        return newuri;
    }

    /**
     * 发送Get请求 https://
     * @param httpPost
     * @return
     */
//	@Override
	public static String sendHttpsGet(String httpsUrl) {
		HttpGet httpGet = new HttpGet(httpsUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
                    .load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);
            
            response = httpClient.execute(httpGet);
            if(200==response.getStatusLine().getStatusCode()) {
            	entity = response.getEntity();
            	responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }
	
	public static BufferedInputStream getGis(String url){
		BufferedInputStream bis = null;
		try {
//		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet requestGet = new HttpGet(url);
		requestGet.setConfig(requestConfig);
		HttpResponse httpResponse = null;
		Map<String, Object> headerMap = Maps.newHashMap();
		// headerMap.put("ETag", "5b2a5ce1-19de8");
		// headerMap.put("Last-Modified", new Date().toString());
		headerMap.put("Cache-Control", "max-age=0");
		headerMap.put("Referer", "http://www.mm131.com/xinggan/4086_2.html");
		headerMap.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36");
		headerMap.put("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		headerMap.put("Accept-Encoding", "gzip, deflate");
		headerMap.put("Accept-Language", "zh-CN,zh;q=0.9");
		headerMap.put("Connection", "keep-alive");
		// headerMap.put("Host", "mg1.mm131.mei");
		headerMap.put("Upgrade-Insecure-Request", "1");
		if (headerMap != null) {
			for (String key : headerMap.keySet()) {
				requestGet.setHeader(key, headerMap.get(key).toString());
			}
		}
		httpResponse = httpClient.execute(requestGet);
		if (httpResponse.getStatusLine().getStatusCode() == 200
				|| httpResponse.getStatusLine().getStatusCode() == 304) {
			HttpEntity entity = httpResponse.getEntity();
			bis = new BufferedInputStream(entity.getContent());
			return bis;
		}
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
		return bis;
	}
}
